package com.coderc.library.widget;

import android.content.Context;
import android.graphics.drawable.Drawable;
import android.os.Handler;
import android.text.Editable;
import android.text.Selection;
import android.text.Spannable;
import android.text.TextWatcher;
import android.util.AttributeSet;
import android.util.Log;
import android.view.MotionEvent;
import android.view.View;
import android.view.animation.Animation;
import android.view.animation.CycleInterpolator;
import android.view.animation.TranslateAnimation;
import android.widget.EditText;
import android.widget.Toast;

import com.coderc.library.R;


/**
 * @author chengs
 * @Create 2016/2/2   9:38
 */
public class CustomEditText extends EditText implements View.OnFocusChangeListener, TextWatcher {

    /**
     * 删除按钮的引用
     */
    private Drawable             mClearDrawable;
    /**
     * 控件是否有焦点
     */
    private boolean              hasFoucs;
    private Context              mContext;
    private int                  cursorPos;
    private String               inputAfterText;
    private boolean              resetText;
    public  TextChangeOnListener mTextChangeOnListener;

    public CustomEditText(Context context) {
        this(context, null);
    }

    public CustomEditText(Context context, AttributeSet attrs) {
        this(context, attrs, android.R.attr.editTextStyle);
    }

    public CustomEditText(Context context, AttributeSet attrs, int defStyleAttr) {
        super(context, attrs, defStyleAttr);
        this.mContext = context;
        init();
    }

    private void init() {
        // 获取EditText的DrawableRight,假如没有设置我们就使用默认的图片
        mClearDrawable = getCompoundDrawables()[2];
        if (mClearDrawable == null) {
            // throw new
            // NullPointerException("You can add drawableRight attribute in XML");
            mClearDrawable = getResources().getDrawable(R.drawable.edittext_background_selector);
        }
        mClearDrawable.setBounds(0, 0, mClearDrawable.getIntrinsicWidth(), mClearDrawable
                .getIntrinsicHeight());
        setClearIconVisible(false);
        setOnFocusChangeListener(this);
        addTextChangedListener(this);
    }

    public void setTextChangedListener(TextChangeOnListener textChangedListener) {
        this.mTextChangeOnListener = textChangedListener;
    }

    @Override
    public boolean onTouchEvent(MotionEvent event) {
        if (event.getAction() == MotionEvent.ACTION_UP) {
            if (getCompoundDrawables()[2] != null) {
                boolean touchable = event.getX() > (getWidth() - getTotalPaddingRight()) &&
                        (event.getX() < ((getWidth() - getPaddingRight())));
                if (touchable) {
                    this.setText("");
                }
            }
        }
        return super.onTouchEvent(event);
    }

    Handler mHandler = new Handler();

    @Override
    public void onFocusChange(View v, boolean hasFocus) {
        this.hasFoucs = hasFocus;
        if (hasFocus) {
            setClearIconVisible(getText().length() > 0);
        } else {
            setClearIconVisible(false);
        }

    }

    protected void setClearIconVisible(boolean visible) {
        Drawable right = visible ? mClearDrawable : null;
        setCompoundDrawables(getCompoundDrawables()[0], getCompoundDrawables()[1], right,
                getCompoundDrawables()[3]);
    }

    @Override
    public void beforeTextChanged(CharSequence s, int start, int count, int after) {
        if (!resetText) {
            cursorPos = getSelectionEnd();
            inputAfterText = s.toString();
        }
    }

    @Override
    public void afterTextChanged(Editable s) {
    }

    @Override
    public void onTextChanged(CharSequence s, int start, int lengthBefore, int lengthAfter) {
        if (hasFoucs) {
            setClearIconVisible(s.length() > 0);
        }
        if (!resetText) {
            if (lengthBefore == 0) {
                CharSequence input = s.subSequence(cursorPos, cursorPos + lengthAfter);
                if (containsEmoji(input.toString())) {
                    resetText = true;
                    Toast.makeText(mContext, "不支持输入表情符号", Toast.LENGTH_SHORT).show();
                    setAnimation();
                    setText(inputAfterText);
                    CharSequence text = getText();
                    if (text instanceof Spannable) {
                        Spannable spanText = (Spannable) text;
                        Selection.setSelection(spanText, spanText.length());
                    }
                }
            }
        } else {
            resetText = false;
        }
        if (mTextChangeOnListener != null) {
            mTextChangeOnListener.onTextChange(s, start, lengthBefore, lengthAfter);
        }
    }

    public void setAnimation() {
        this.setAnimation(shakeAnimation(5));
    }

    public Animation shakeAnimation(int count) {
        TranslateAnimation translateAnimation = new TranslateAnimation(0, 10, 0, 0);
        translateAnimation.setInterpolator(new CycleInterpolator(count));
        translateAnimation.setDuration(1000);
        return translateAnimation;
    }

    public boolean containsEmoji(String source) {
        int len = source.length();
        for (int i = 0; i < len; i++) {
            char codePoint = source.charAt(i);
            if (!isEmojiCharacter(codePoint)) {
                return true;
            }
        }
        return false;
    }

    private boolean isEmojiCharacter(char codePoint) {
        int b = codePoint;
        Log.e("Test", Integer.toHexString(b));
        return (codePoint == 0x0) || (codePoint == 0x9) || (codePoint == 0xA) || (codePoint ==
                0xD) || ((codePoint >= 0x20) && (codePoint <= 0xD7FF) && (codePoint != 0x263a))
                || ((codePoint >= 0xE000) && (codePoint <= 0xFFFD)) || ((codePoint >= 0x10000) &&
                (codePoint <= 0x10FFFF));
    }

    public interface TextChangeOnListener {
        void onTextChange(CharSequence s, int start, int lengthBefore, int lengthAfter);
    }

}
